//
//  SmileHttpTool.m
//  chengguaApp
//
//  Created by 微笑吧阳光 on 2018/4/4.
//  Copyright © 2018年 SmileFans. All rights reserved.
//

#import "SmileHttpTool.h"
#import "AFNetworking.h"
#import "UIKit+AFNetworking.h"
#import "SmileHTTPSessionManager.h"
#import "SmileNetWorkState.h"
#import "YINetWorkAPIGenerate.h"
#import "sys/utsname.h"
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#import "NSString+Hash.h"
#import "ZDBKeychainTool.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>


#define KNetStatus @"statusCode"
#define KNetData @"data"
#define KNetMsg @"message"

@interface SmileHttpTool ()

/**注释---200成功 204 成功没有数据 code message */
@property (nonatomic, strong) SmileHTTPSessionManager *manager;
@end
@implementation SmileHttpTool

- (SmileHTTPSessionManager *)manager {
    if (!_manager) {
        _manager = [SmileHTTPSessionManager shareManager];
    }
    return _manager;
}

//创建单例
+ (SmileHttpTool *) sharedInstance
{
    static  SmileHttpTool *sharedInstance = nil ;
    static  dispatch_once_t onceToken;
    dispatch_once (& onceToken, ^ {
        //初始化自己
        sharedInstance = [[self alloc] init];
        //实例化请求对象
        sharedInstance.manager = [SmileHTTPSessionManager shareManager];
    });
    return  sharedInstance;
}
#pragma mark - 单例模式请求API
#pragma mark - GET
- (void)GET:(NSString *)URLString
 parameters:(id)parameters
     origin:(BOOL)isOrigin
    success:(NetworkSuccessBlock)success
    failure:(NetworkFailureBlock)failure
{
if (!kStringIsEmpty([[DJLoginHelper sharedInstance] cj_token])) {
       [self.manager.requestSerializer setValue:[[DJLoginHelper sharedInstance] cj_token] forHTTPHeaderField:@"Authorization"];
    }else{
        [self.manager.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
    }
    [self.manager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"mobileType"];
     [self set_CommenHeaderRequestDataWith:URLString];
    [self.manager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       
               NSError *errorData;
                NSString* strdata = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];//在将NSString类型转为NSData
                 NSData * data =[strdata dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
                NSLog(@"responseObject---%@",dict);
               // success(0,@"",dict);
                NSDictionary *responseDict = [NSDictionary dictionaryWithDictionary:dict];
                if (isOrigin) {
                    if (success) {
                             success(200,@"",responseDict);
                    }
                    return ;
                }
        //        //[responseDict[KNetStatus] integerValue];
                NSInteger status = [responseDict jsonInteger:KNetStatus];
                NSString * msg = responseDict[KNetMsg];
                id data2 = responseDict[KNetData];
               
                if (success) {
                    success (status,msg,data2);
                }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(nil, error);
        }
    }];
}

- (void)GET_Data:(NSString *)URLString
 parameters:(id)parameters
     origin:(BOOL)isOrigin
    success:(NetworkSuccessWithTaskBlock)success
    failure:(NetworkFailureBlock)failure
{
if (!kStringIsEmpty([[DJLoginHelper sharedInstance] cj_token])) {
        [self.manager.requestSerializer setValue:[[DJLoginHelper sharedInstance] cj_token] forHTTPHeaderField:@"Authorization"];
    }else{
        [self.manager.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
    }
    [self.manager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"mobileType"];
     [self set_CommenHeaderRequestDataWith:URLString];
    [self.manager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        success(0,task,responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(nil, error);
        }
    }];
}

#pragma mark - POST
- (void)POST:(NSString *)URLString
  parameters:(id)parameters
      origin:(BOOL)isOrigin
     success:(NetworkSuccessBlock)success
     failure:(NetworkFailureBlock)failure
{
        if (!kStringIsEmpty([[DJLoginHelper sharedInstance] cj_token])) {
            NSLog(@"===>%@",[[DJLoginHelper sharedInstance] cj_token]);
           [self.manager.requestSerializer setValue:[[DJLoginHelper sharedInstance] cj_token] forHTTPHeaderField:@"Authorization"];
        }else{
            [self.manager.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
        }
        [self.manager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"mobileType"];
    
    [self set_CommenHeaderRequestDataWith:URLString];
    [self.manager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *errorData;
        NSString* strdata = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];//在将NSString类型转为NSData
         NSData * data =[strdata dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
        NSLog(@"responseObject---%@",dict);
       // success(0,@"",dict);
        NSDictionary *responseDict = [NSDictionary dictionaryWithDictionary:dict];
        if (isOrigin) {
            if (success) {
                     success(200,@"",responseDict);
            }
            return ;
        }
//        //[responseDict[KNetStatus] integerValue];
        NSInteger status = [responseDict jsonInteger:KNetStatus];
        NSString * msg = responseDict[KNetMsg];
        id data2 = responseDict[KNetData];
        if (status==2) {
            dispatch_async(dispatch_get_main_queue(), ^{
            
                [[DJLoginHelper sharedInstance] loginOutToken];
                
            });
            
        }
        if (success) {
            success (status,msg,data2);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [ZBDUnit showMessage:@"请求超时，请检查网络"];
        if (failure) {
            failure(nil, error);
        }
    }];
}


-(void)set_CommenHeaderRequestDataWith:(NSString *)requestUrl{
    
    
    NSString * code6Str = [self getVerificationCode];
    NSString * requestUrlStr = requestUrl;
    NSString * macUuID = [NSString stringWithFormat:@"IOS-%@",[ZDBKeychainTool getDeviceIDInKeychain]];
    NSString * mobType = @"iOS";
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    NSString*timeString = [NSString stringWithFormat:@"%0.f", a/1000];//转为字符型
    NSString * hacStr = @"";
    if (!kStringIsEmpty([[DJLoginHelper sharedInstance] cj_token])) {
               NSLog(@"===>%@",[[DJLoginHelper sharedInstance] cj_token]);
              [self.manager.requestSerializer setValue:[[DJLoginHelper sharedInstance] cj_token] forHTTPHeaderField:@"Authorization"];
             hacStr =   [NSString stringWithFormat:@"requestUrl=%@&mac=%@&time=%@&authorization=%@",requestUrlStr,macUuID,timeString,[[DJLoginHelper sharedInstance] cj_token]];
           }else{
               [self.manager.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
               hacStr =   [NSString stringWithFormat:@"requestUrl=%@&mac=%@&time=%@",requestUrlStr,macUuID,timeString];
    }
    
    [self.manager.requestSerializer setValue:macUuID forHTTPHeaderField:@"mac"];
    [self.manager.requestSerializer setValue:mobType forHTTPHeaderField:@"mobileType"];
    [self.manager.requestSerializer setValue:code6Str forHTTPHeaderField:@"randomInfo"];
    [self.manager.requestSerializer setValue:timeString forHTTPHeaderField:@"time"];
    
    NSString * siyao = [self hmacSHA256WithSecret:@"zhangduibao_public_key" content:hacStr];
    NSString * sign = [self hmacSHA256WithSecret:siyao content:hacStr];
    [self.manager.requestSerializer setValue:sign forHTTPHeaderField:@"sign"];
    
    
    
    
}


#pragma mark - 请求API
+ (void)httpWork_get:(NSString *)url parameters:(NSMutableDictionary *)parameters progress:(void (^)(NSProgress *))progress success:(void (^)(id))success successOther:(void (^)(id))successOther failure:(void (^)(NSError *))failure endRfresh:(void (^)(void))endRfresh showLoadingView:(BOOL)showLoadingView {
    
    if ([SmileNetWorkState checkNetWorkState].isRightNetwork == YES) {
        if (showLoadingView) {
            //加载动画
            
        }
        
        [[[SmileHttpTool alloc] init].manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            if (progress) {
                progress(uploadProgress);
            }
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (showLoadingView) {//隐藏动画
                
            }
            if (endRfresh) {
                endRfresh();
            }
            
            if (responseObject) {
            //NSLog(@"💗--responseObject--%@",responseObject);
                //具体看项目接口返回的层级
                NSInteger code = [[responseObject valueForKey:@"status"] integerValue];
                
                if (code == 200) {
                    
                    if (success) {
                        success(responseObject);
                    }
                    
                } else if (code == 100) {//比如全局统一的，直接在里面弹窗处理
                    
                } else {
                    
                    if (code == 204) {//需要弹窗提示充值
                        if (successOther) {
                            successOther(responseObject);
                        }
                    } else {
                        //提示吐司窗口
                    }
                }
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (showLoadingView) {//隐藏动画
                
            }
            if (endRfresh) {
                endRfresh();
            }
            if (failure) {
                failure(error);
            }
        }];
    } else {
        //没有网络
    }
    
    
}

+ (void)httpWork_post:(NSString *)url parameters:(NSMutableDictionary *)parameters progress:(void (^)(NSProgress *))progress success:(void (^)(id))success successOther:(void (^)(id))successOther failure:(void (^)(NSError *))failure endRfresh:(void (^)(void))endRfresh showLoadingView:(BOOL)showLoadingView {
    
    
//    responseObject--{
//        message = "\U767b\U5f55\U5931\U8d25";
//        result = "";
//        status = 404;
//    }
    if ([SmileNetWorkState checkNetWorkState].isRightNetwork == YES) {
        if (showLoadingView) {
            //加载动画
        }
        
        [[[SmileHttpTool alloc] init].manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            if (progress) {
                progress(uploadProgress);
            }
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (showLoadingView) {//隐藏动画
                
            }
            if (endRfresh) {
                endRfresh();
            }
            
            if (responseObject) {
                //具体看项目接口返回的层级
                NSInteger code = [[responseObject valueForKey:@"status"] integerValue];
                
                if (code == 0) {
                    
                    if (success) {
                        success(responseObject);
                    }
                    
                } else if (code == 100) {//比如全局统一的，直接在里面弹窗处理
                    
                } else {
                    
                    if (code == 200) {//需要弹窗提示充值
                        if (successOther) {
                            successOther(responseObject);
                        }
                    } else {
                        //提示吐司窗口
                    }
                }
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (showLoadingView) {//隐藏动画
                
            }
            if (endRfresh) {
                endRfresh();
            }
            if (failure) {
                failure(error);
            }
        }];
    } else {
        //没有网络
    }
}
/**
 获取七牛上传的Token
 
 @param typeStr 获取什么类型的token
 @param resultBlock 成功结果回调
 */
-(void)getTokenFromQiNiu:(NSString *)typeStr
             resultBlock:(void(^)(BOOL isSuccess, NSString * token))resultBlock{
    
//    NSString * url = [[YINetWorkAPIGenerate sharedInstance] API:@"qiNiuYun_getToken"];
    NSString * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"qiNiuYun_getToken"];
    [[SmileHttpTool sharedInstance] POST:url parameters:nil origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
     [self set_CommenHeaderRequestDataWith:url];
    NSDictionary *responseDict = [NSDictionary dictionaryWithDictionary:responseObject];
    NSInteger status = [responseDict jsonInteger:KNetStatus];
           //    NSString * msg = responseDict[KNetMsg];
    NSDictionary * data2 = responseDict[KNetData];
        NSString *  token = [data2 jsonString:@"token"];
        if (status==0) {
            if (resultBlock) {
                           resultBlock(YES,token);
                       }
        }else{
            if (resultBlock) {
                             resultBlock(NO,responseDict[@"message"]);
                         }
            
        }
        
        
    } failure:^(id responseObject, NSError *error) {
                if (resultBlock) {
                    resultBlock(NO,@"");
                }
    }];

    
    
    
}

-(void)request256TextBlock:(void(^)(NSInteger code, NSString * message))resultBlock{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
      manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //   [_manager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"mobileType"];
      manager.responseSerializer = [AFHTTPResponseSerializer serializer];
      manager.requestSerializer.stringEncoding = kCFStringEncodingUTF8;
      manager.requestSerializer.timeoutInterval = 600;
      _manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
       [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
      manager.responseSerializer.acceptableContentTypes =[NSSet  setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/plain",@"text/html",@"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",nil];
    
    [manager.requestSerializer setValue:@"IOS-58:02:03:04:05:06" forHTTPHeaderField:@"mac"];
    [manager.requestSerializer setValue:@"IOS" forHTTPHeaderField:@"mobileType"];
    [manager.requestSerializer setValue:@"Asd651" forHTTPHeaderField:@"randomInfo"];
    [manager.requestSerializer setValue:@"1589725384863" forHTTPHeaderField:@"time"];
    
    
    NSString * urlStr = @"http://47.240.163.155/zdb/mobile/userInfo/login";
    NSString * hacStr = [NSString stringWithFormat:@"requestUrl=%@&mac=%@&time=%@",urlStr,@"IOS-58:02:03:04:05:06",@"1589725384863"];
    NSString * siyao = [self hmacSHA256WithSecret:@"zhangduibao_public_key" content:hacStr];
    NSString * sign = [self hmacSHA256WithSecret:siyao content:hacStr];
    [manager.requestSerializer setValue:sign forHTTPHeaderField:@"sign"];
    //zhangduibao_public_key
//    私钥生成规则:requestUrl+Time+Mac+authorizatio字符串+公钥生成采用HSA256加密转大写;
//    签名生成规则：requestUrl+Time+Mac+authorizatio+私钥HSA256加密转大写
    //VicFans http://47.240.163.155/zdb/
    
    NSMutableDictionary * diccc = [NSMutableDictionary dictionary];
    [diccc setValue:@"13175110051" forKey:@"userName"];
    [diccc setValue:@"aa123456" forKey:@"passWord"];
    [manager POST:urlStr parameters:diccc progress:^(NSProgress * _Nonnull uploadProgress) {} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"success----%@",responseObject);
        NSError *errorData;
               NSString* strdata = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];//在将NSString类型转为NSData
                NSData * data =[strdata dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
               NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
        NSLog(@"success----%@",dict);
        NSLog(@"success--message---%@",[dict jsonString:@"message"]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       NSLog(@"error-----%@",error);
    }];

}
- (NSString *)getVerificationCode
{
    NSArray *strArr = [[NSArray alloc]initWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",nil] ;
    NSMutableString *getStr = [[NSMutableString alloc]initWithCapacity:5];
    for(int i = 0; i < 6; i++) //得到六位随机字符,可自己设长度
    {
        int index = arc4random() % ([strArr count]);  //得到数组中随机数的下标
        [getStr appendString:[strArr objectAtIndex:index]];
        
    }
    NSLog(@"验证码:%@",getStr);
    return getStr;
}
/**
 *  加密方式,MAC算法: HmacSHA256
 *
 *  @param secret       秘钥
 *  @param content    要加密的文本
 *
 *  @return 加密后的字符串
 */
- (NSString *)hmacSHA256WithSecret:(NSString *)secret content:(NSString *)content
{
    const char *cKey  = [secret cStringUsingEncoding:NSASCIIStringEncoding];
    const char *cData = [content cStringUsingEncoding:NSUTF8StringEncoding];// 有可能有中文 所以用NSUTF8StringEncoding -> NSASCIIStringEncoding
    unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)];
    const unsigned char *buffer = (const unsigned char *)[HMACData bytes];
    NSMutableString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2];
    for (int i = 0; i < HMACData.length; ++i){
        [HMAC appendFormat:@"%02x", buffer[i]];
    }
    return [HMAC uppercaseString];
}


@end
